<template>
    <div class="tshirt-editor">
      <button @click="downloadCanvasAsPNG">Download Image</button>
  
      <canvas id="tshirtCanvas" width="2000" height="2667"></canvas>
    </div>
  </template>
  
  <script>
  import { fabric } from 'fabric';
  import huli from './huli.png'
  import bg from './black.png'
  
  export default {
    name: 'TshirtEditor',
    mounted() {
      this.initializeCanvas();
    },
    methods: {
      initializeCanvas() {
        this.canvas = new fabric.Canvas('tshirtCanvas');
  
        // 绘制一个简单的衣服图案（可以替换成真实的衣服图片）
        fabric.Image.fromURL('https://i.postimg.cc/3rpJTwbz/3.png', (img) => {
          console.log(img);
          img.crossOrigin = 'Anonymous';
          img.scaleToWidth(600);
          img.scaleToHeight(600);
          img.set({
            left: 0,
            top: 0,
            selectable: false,
          });
          // canvas.add(img);
          this.canvas.setBackgroundImage(img, this.canvas.renderAll.bind(this.canvas));
        },{ crossOrigin: 'Anonymous' });
  
        // 添加一个 logo 并使其可拖拽
        fabric.Image.fromURL('https://i.postimg.cc/0j4TL71b/1.png', (img) => {
          img.crossOrigin = 'Anonymous';
          img.scaleToWidth(150);
          img.scaleToHeight(150);
          img.set({
            left: 225,
            top: 180,
            selectable: true, // 使图片可拖拽
            hasControls: true, // 允许缩放、旋转控制
          });
          this.canvas.add(img);
          this.canvas.bringToFront(img);
          this.canvas.renderAll();
        },{ crossOrigin: 'Anonymous' });
      },
      downloadCanvasAsPNG() {
        const dataURL = this.canvas.toDataURL({
          format: 'png',  // 输出为 PNG 格式
          quality: 1,     // 设置图像质量
        });
  
        // 创建一个下载链接
        const link = document.createElement('a');
        link.href = dataURL;  // 设置链接指向合成图像
        link.download = 'tshirt-design.png';  // 设置下载的文件名
  
        // 模拟点击下载链接
        link.click();
      },
    },
  };
  </script>
  
  <style scoped>
  .tshirt-editor {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 100px;
  }
  canvas {
    border: 1px solid #000;
  }
  </style>
  